package com.ip.user.api;

import com.ip.user.models.dto.EmailCaptchaDTO;
import com.ip.user.models.service.EmailCaptchaService;
import com.ip.user.models.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 邮箱验证码控制器
 */
@RestController
@RequestMapping("/api/captcha")
@CrossOrigin
public class EmailCaptchaController {
    
    private static final Logger logger = LoggerFactory.getLogger(EmailCaptchaController.class);
    
    @Autowired
    private EmailCaptchaService emailCaptchaService;
    
    @Autowired
    private SysUserService sysUserService;
    
    /**
     * 获取邮箱验证码
     */
    @PostMapping("/email")
    public ResponseEntity<?> getEmailCaptcha(@RequestParam("email") String email,
                                             @RequestParam(value = "captchaType", defaultValue = "忘记密码") String captchaType) {
        logger.info("收到获取验证码请求，邮箱: {}, 类型: {}", email, captchaType);
        Map<String, Object> captchaResult = emailCaptchaService.generateCaptcha(email, captchaType);
        
        if (captchaResult.containsKey("success") && (Boolean) captchaResult.get("success")) {
            return ResponseEntity.ok(captchaResult);
        } else {
            return ResponseEntity.badRequest().body(captchaResult);
        }
    }
    
    /**
     * 验证邮箱验证码 - 验证成功后自动重置密码
     */
    @PostMapping("/email/verify")
    public ResponseEntity<?> verifyEmailCaptcha(
            @RequestParam(value = "email", required = false) String email,
            @RequestParam(value = "captcha", required = false) String captcha,
            @RequestParam(value = "captchaType", defaultValue = "忘记密码") String captchaType) {
        
        logger.info("收到验证码验证请求，邮箱: {}, 验证码: {}, 类型: {}", email, captcha, captchaType);
        
        // 检查必要参数
        if (email == null || email.isEmpty() || captcha == null || captcha.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "邮箱和验证码不能为空");
            return ResponseEntity.badRequest().body(errorResponse);
        }
        
        // 创建EmailCaptchaDTO对象并填充数据
        EmailCaptchaDTO emailCaptchaDTO = new EmailCaptchaDTO();
        emailCaptchaDTO.setEmail(email);
        emailCaptchaDTO.setCaptcha(captcha);
        emailCaptchaDTO.setCaptchaType(captchaType);
        
        // 验证验证码
        boolean isValid = emailCaptchaService.verifyCaptcha(emailCaptchaDTO);
        
        Map<String, Object> response = new HashMap<>();
        if (isValid) {
            // 验证码正确，自动重置密码
            logger.info("验证码验证成功，开始重置邮箱为 {} 的用户密码", email);
            boolean resetSuccess = sysUserService.resetPasswordByEmail(email);
            if (resetSuccess) {
                logger.info("邮箱为 {} 的用户密码重置成功", email);
                response.put("success", true);
                response.put("message", "验证成功，密码已重置为身份证号后六位");
            } else {
                logger.warn("邮箱为 {} 的用户密码重置失败", email);
                response.put("success", false);
                response.put("message", "验证成功，但密码重置失败");
            }
        } else {
            logger.warn("验证码验证失败，邮箱: {}, 验证码: {}, 类型: {}", email, captcha, captchaType);
            response.put("success", false);
            response.put("message", "验证码错误或已过期");
        }
        
        return ResponseEntity.ok(response);
    }
}